﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace CPPEI.Coolzon.Designer.Views
{
    public static class AddFolderCommand
    {
        public static void Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (UIContext.Current.SolutionNode != null && (UIContext.Current.SolutionNode.NodeStatus == NodeStatus.CheckOut || UIContext.Current.SolutionNode.NodeStatus == NodeStatus.Add))
            {
                AddFolder();
            }
            else
            {
                List<SolutionTreeViewNode> nodeList = new List<SolutionTreeViewNode>();
                nodeList.Add(UIContext.Current.SolutionNode);
                CheckOutThread.Start(nodeList, ReportProgress, Completed);
            }
        }
        public static void CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (UIContext.Current.CurrentSelectedNode != null && (UIContext.Current.CurrentSelectedNode.NodeType == NodeType.Solution || UIContext.Current.CurrentSelectedNode.NodeType == NodeType.Folder))
            {
                e.CanExecute = true;
            }
            else
            {
                e.CanExecute = false;
            }
        }
        public static void ReportProgress(Guid id, string name, int current, int total)
        {

        }

        public static void Completed(bool HasError, int successed, int total)
        {
            if (HasError)
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() => {
                    Coolzon.UI.CustomMessageBox.ShowError("方案签出失败，可能存在新版本。");
                });
                return;
            }
            
            if (UIContext.Current.SolutionNode != null && (UIContext.Current.SolutionNode.NodeStatus == NodeStatus.CheckOut || UIContext.Current.SolutionNode.NodeStatus == NodeStatus.Add))
            {
                AddFolder();
            }
        }

        private static void AddFolder()
        {
            string folderName = "新建文件夹";
            folderName = folderName + (++UIContext.Current.CurrentSolution.IdSeed);
            while (UIContext.Current.CurrentSolution.ExistFolder(UIContext.Current.CurrentSelectedNode.FolderID, folderName))
            {
                folderName = folderName + (++UIContext.Current.CurrentSolution.IdSeed);
            }
            Event.UI.UIEventBus.Publish(new Event.UI.UICreateFolderEvent(folderName));
        }
    }
}
